package com.growthserver.kafkaMQ;

import com.alibaba.fastjson.JSON;
import com.growthserver.entity.TMemberEntity;
import com.growthserver.entity.TMemberLevelEntity;
import com.growthserver.entity.TTaskComboDoRecordEntity;
import com.growthserver.entity.TTaskRuleDoRecordEntity;
import com.growthserver.mapper.IntegralGrowthMapper;
import com.growthserver.mapper.TaskCenterMapper;
import com.growthserver.service.AppletService;
import com.growthserver.service.EquityCenterService;
import com.growthserver.util.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 进行积分明细数据入库操作
 */
@Component
public class IntegralGrowthInfoConsumer {

    private final Logger LOGGER = LoggerFactory.getLogger(IntegralGrowthInfoConsumer.class);

    /**
     * 任务
     */
    @Autowired
    private TaskCenterMapper taskCenterMapper;
    @Autowired
    private IntegralGrowthMapper integralGrowthMapper;

    @Autowired
    private EquityCenterService equityCenterService;

    @Autowired
    private AppletService appletService;

    @Transactional(rollbackFor = Exception.class)
    @KafkaListener(topics = "${internalConsumerTopic:TOPIC_INTERNAL_MY_CONSUMER}", groupId = "${kafkaGroupId:KAFKA_GROUP_MY_GROWTH}")
    public void internalGrowthConsumer(String message) {
        LOGGER.info("进行积分明细数据入库操作消费:{}", message);
        TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity = JSON.parseObject(message, TTaskRuleDoRecordEntity.class);
        //校验积分值是否大于发放积分
        String check = integralGrowthMapper.integralBudgetCheck(tTaskRuleDoRecordEntity.getBudgetRequestNum(), tTaskRuleDoRecordEntity.getIntegralValue());
        if(check != null && check.equals("0")){
            LOGGER.info("当前积分池中积分不足以,进行积分发放");
            return ;
        }
        //如果不发积分,则不进行扣减
        // TODO 积分预算进行,发放扣减 更新 积分池,需要预审单号
        if(tTaskRuleDoRecordEntity.getIntegralValue() != null){
            integralGrowthMapper.updateIntegralBudge(tTaskRuleDoRecordEntity.getBudgetRequestNum(), tTaskRuleDoRecordEntity.getIntegralValue());
        }
        //1积分成长值数据入库
        integralGrowthMapper.insertRuleLog(tTaskRuleDoRecordEntity);
        //更新会员信息表数据
        updateMemberInfo(tTaskRuleDoRecordEntity);
        //是否有对应的社区任务 有则写入社区任务日志表
        recodeComboTask(tTaskRuleDoRecordEntity);
        //判断是否全部社区任务完成
        completeComboTask(tTaskRuleDoRecordEntity.getTaskType());
    }


    /**
     * 更新会员信息
     */
    private void updateMemberInfo(TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity){
        // 查询 日志表总积分,总成长值
        HashMap<String, String> map = integralGrowthMapper.selectTotalIntegralGrowthValue(tTaskRuleDoRecordEntity.getUserId());
        //获取用户等级对应成长值,算出当前用户等级
        String growthValue = String.valueOf(map.get("growthValue"));
        String integralValue = String.valueOf(map.get("integralValue"));
        //查询会员信息类型
        TMemberEntity userLevel = appletService.getUserLevel(tTaskRuleDoRecordEntity.getUserId());
        TMemberLevelEntity tMemberLevelEntity = equityCenterService.getUserLeveL(growthValue, userLevel.getUserType());
        if (tMemberLevelEntity != null) {
            // 更新会员信息表
            TMemberEntity tMemberEntity = new TMemberEntity();
            tMemberEntity.setUserId(tTaskRuleDoRecordEntity.getUserId());
            tMemberEntity.setTotalGrowthValue(growthValue.split("\\.")[0]);
            tMemberEntity.setTotalIntegralValue(integralValue.split("\\.")[0]);
            //如果编号不相等 ,那么意味着升级
            if(!userLevel.getLevelNum().equals(tMemberLevelEntity.getLevelNum())){
                // 添加用户等级
                String memberLevel = integralGrowthMapper.selectByLevelEnum(tMemberLevelEntity.getLevelNum());
                tMemberEntity.setMemberLevel(memberLevel);
                tMemberEntity.setLevelName(tMemberLevelEntity.getLevelName());
                tMemberEntity.setLevelNum(tMemberLevelEntity.getLevelNum());
                //获取 对应等级的 有效期时长
                String levelPeriodTime = tMemberLevelEntity.getLevelPeriodTime();
                //更新用户有效期
                Date date = DateUtils.addDateYears(new Date(), Integer.parseInt(levelPeriodTime));
                tMemberEntity.setExpDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            }
            equityCenterService.updateMemberInfo(tMemberEntity);
        }
    }

    /**
     * 社区任务写入记录表中
     */
    private void recodeComboTask(TTaskRuleDoRecordEntity tTaskRuleDoRecordEntity){
        List<HashMap<String, String>> listMap = taskCenterMapper.selectTaskComboByType(tTaskRuleDoRecordEntity.getActionType());
        for (HashMap<String, String> stringStringHashMap : listMap
        ) {
            String taskId = stringStringHashMap.get("taskId");
            String taskGiftUrl = stringStringHashMap.get("taskGiftUrl");
            String taskType = tTaskRuleDoRecordEntity.getTaskType();
            //查询表是否存在 taskId 和type
            String p = taskCenterMapper.selectByTaskIdAndTaskType(taskId, taskType,tTaskRuleDoRecordEntity.getUserId());
            if(StringUtils.isBlank(p)){
                TTaskComboDoRecordEntity tTaskComboDoRecordEntity = new TTaskComboDoRecordEntity();
                tTaskComboDoRecordEntity.setTaskId(taskId);
                tTaskComboDoRecordEntity.setUserId(tTaskRuleDoRecordEntity.getUserId());
                tTaskComboDoRecordEntity.setTaskType(tTaskRuleDoRecordEntity.getTaskType());
                tTaskComboDoRecordEntity.setActionType(tTaskRuleDoRecordEntity.getActionType());
                tTaskComboDoRecordEntity.setIntegralType(tTaskRuleDoRecordEntity.getIntegralType());
                tTaskComboDoRecordEntity.setIntegralValue(tTaskRuleDoRecordEntity.getIntegralValue());
                tTaskComboDoRecordEntity.setGrowthValue(tTaskRuleDoRecordEntity.getGrowthValue());
                tTaskComboDoRecordEntity.setTaskGiftUrl(taskGiftUrl);
                tTaskComboDoRecordEntity.setCreator(tTaskRuleDoRecordEntity.getCreator());
                tTaskComboDoRecordEntity.setCreatedName(tTaskRuleDoRecordEntity.getCreatedName());
                taskCenterMapper.taskComboRecord(tTaskComboDoRecordEntity);
            }else {
                taskCenterMapper.updateTaskComboRecord(taskId,taskType);
            }
        }
    }

    private void completeComboTask(String Type){
        //根据Type查询对应的社区任务
        //通过任务ID 查询对应的社区任务是否全部完成
    }
}
